<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\admin\model\UserModel;
use cmf\controller\HomeBaseController;
use think\Db;
use think\Request;

class IndexController extends HomeBaseController
{
    public function _initialize()
    {
        parent::_initialize();
    }
    //首页
    public function index()
    {
        $portal_id = session('PORTRL_ID');
        if (!empty($portal_id))
        {
            //已经登录
            $por_id['id'] = $portal_id;
            $branch_id = Db::name('user')->where($por_id)->value('branch_id');
            if ($branch_id == 0)
            {
                $branch_id = 1;
            }

            //查出一级id
            $parent = Db::name('portal_category')->where('id', $branch_id)->field('id,name,parent_id')->find();
            if (!empty($parent['parent_id']))
            {
                $whe_parent['id'] = $parent['parent_id'];
                $whe_parent['status'] = 1;
                $one_depa = Db::name('portal_category')->where($whe_parent)->field('id,name')->find();
            }
            else
            {
                $one_depa = $parent;
            }

            //查出一级文章
            $whe_one['category_id'] = $one_depa['id'];
            $whe_one['status'] = 1;
            $one_post_id = Db::name('portal_category_post')->where($whe_one)->value('post_id');
            $plate_whe = [
                'id' => $one_post_id,
                'post_status' => 1,
                'is_top' => 1,
                'delete_time' => 0,

            ];
            $plate = Db::name('portal_post')->where($plate_whe)->field('id,thumbnail,post_excerpt,post_title,more')->find();
            $more = (json_decode($plate['more'], true));
            $video = $more['video'];
            $plate['more'] = $video;
            //查出所有二级分类名
            $project = Db::name('portal_category')->where('parent_id', $one_depa['id'])->field('id,name')->select();

            //查出二级分类文章
            $project_id_res = null;
            $project_name_res = null;
            foreach ($project as $k => $v)
            {
                $project_id_res[] = $v['id'];
                $project_name_res[] = $v['name'];
            }
            $post_id_res = Db::name('portal_category_post')->whereIn('category_id', $project_id_res)->where('status', 1)->field('post_id')->select();
            $post_res = [];
            foreach ($post_id_res as $k => $v)
            {
                $post_res[] = $v['post_id'];
            }
            $whe = [
                'post_status' => 1,
                'delete_time' => 0,
                'is_top' => 1,
            ];
            $project_res = Db::name('portal_post')->whereIn('post_title', $project_name_res)->whereIn('id', $post_res)->where($whe)->field('id,thumbnail,post_excerpt,post_title')->select();

            $this->assign([
                //板块文章
                'plate' => $plate,
                //所有项目文章
                'project_res' => $project_res,
            ]);
            return $this->fetch('index:index');
        }
        else
        {
            return $this->fetch(":login");
        }
    }

    //忘记密码页
    public function modifyPass()
    {
        return $this->fetch(':find_password');
    }

    //注册页
    public function reg()
    {
        return $this->fetch(':register');
    }

    //注册
    public function register(Request $resquest)
    {
        $parameter = $resquest->param();
        $email = $parameter['email'];
        if ($parameter['place'] == 1)
        {
            $parameter['place'] = '管理员';
        }
        elseif ($parameter['place'] == 2)
        {
            $parameter['place'] = '总经理';
        }
        elseif ($parameter['place'] == 3)
        {
            $parameter['place'] = '项目总监';
        }
        else
        {
            $parameter['place'] = '员工';
        }

        $bankuai_id = Db::name('portal_category')->where(['parent_id' => 0, 'name' => $parameter['bankuai_id']])->value('id');
        if (empty($bankuai_id))
        {
            return json(['status' => 0, 'info' => '板块名不正确!!!']);
        }
        $project_id = Db::name('portal_category')->where(['parent_id' => $bankuai_id, 'name' => $parameter['project']])->value('id');
        if (empty($project_id))
        {
            return json(['status' => 0, 'info' => '项目名不正确!!!']);
        }
        //判断邮箱是否存在
        $res = Db::name('user')->where('user_email', $email)->value('user_email');
        if (!empty($res))
        {
            return json(['status' => 0, 'info' => '邮箱账号已存在!!!']);
        }
        //获取架构id
        $fram_whe = [
            'parent_id' => $bankuai_id,
            'id' => $project_id,
        ];
        $framework_id = Db::name('portal_category')->where($fram_whe)->value('id');
        if (empty($framework_id))
        {
            return json(['status' => 0, 'info' => '未找到此项目!!!']);
        }
        $user_data = [];
        $user_data = [
            'user_login' => $parameter['username'],
            'user_email' => $parameter['email'],
            'authority' => $parameter['place'],
            'create_time' => time(),
            'mobile' => $parameter['phone'],
            'user_pass' => cmf_password($parameter['pass']),
            'branch_id' => 1,
            'user_status' => 2,
        ];
        if ($parameter['place'] == '管理员')
        {
            $branch_id = 0;
        }
        elseif ($parameter['place'] == '总经理')
        {
            $branch_id = $bankuai_id;
        }
        elseif ($parameter['place'] == '项目总监')
        {
            $branch_id = $framework_id;
        }
        else
        {
            $branch_id = $framework_id;
            //查出板块id
            $parent_id = Db::name('portal_category')->where('id', $framework_id)->value('parent_id');
        }
        $user_data['user_status'] = 2;
        $user_data['branch_id'] = $branch_id;
        $user = Db::name('user')->insert($user_data);
        if ($user)
        {
            return json(['status' => 1, 'info' => '注册成功,是否跳转到登录页面?']);
        }
        else
        {
            return json(['status' => 0, 'info' => '注册失败!!!']);
        }
    }

    /**
     * 前台登陆界面
     */
    public function login()
    {
        $portal_id = session('PORTRL_ID');
        if (!empty($portal_id))
        {
            //已经登录
            $this->success(lang('已经登录,正在跳转!'), url("portal/Index/index"));
        }
        else
        {
            return $this->fetch(":login");
        }
    }

    /**
     * 登录验证
     */
    public function doLogin()
    {
        if (hook_one('admin_custom_login_open'))
        {
            $this->error('您已经通过插件自定义后台登录！');
        }

        $captcha = $this->request->param('captcha');
        if (empty($captcha))
        {
            $this->error(lang('CAPTCHA_REQUIRED'));
        }
        //验证码
        if (!cmf_captcha_check($captcha))
        {
            $this->error(lang('CAPTCHA_NOT_RIGHT'));
        }

        $name = $this->request->param("username");
        if (empty($name))
        {
            $this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
        }
        $pass = $this->request->param("password");
        if (empty($pass))
        {
            $this->error(lang('PASSWORD_REQUIRED'));
        }
        //判断登录状态
        $where['user_status'] = 2;
        $where['user_email'] = $name;
        $status = Db::name('user')->where($where)->value('id');
        //用户状态未确定不给登录
        if ($status)
        {
            $this->error(lang('账号未通过审核,请等待上级审核!!!'));
        }
        unset($where['user_status']);
        //判断访问时间
        $authority = ['admin', '管理员', '总经理', '项目总监'];
        $user_access = Db::name('user')->where($where)->field('authority,access_time')->find();
        if (!in_array($user_access['authority'], $authority))
        {
            if ($user_access['access_time'] < time())
            {
                session('PORTRL_ID', null);
                $this->error(lang('账号未通过登录审核,请等待上级审核!!!'));
            }
        }

        $result = Db::name('user')->where($where)->find();
        if (!empty($result) && $result['user_type'] == 1)
        {
            if (cmf_compare_password($pass, $result['user_pass']))
            {
                $groups = Db::name('RoleUser')
                    ->alias("a")
                    ->join('__ROLE__ b', 'a.role_id =b.id')
                    ->where(["user_id" => $result["id"], "status" => 1])
                    ->value("role_id");
                //登入成功页面跳转
                session('PORTRL_ID', $result["id"]);
                session('name', $result["user_login"]);
                $result['last_login_ip'] = get_client_ip(0, true);
                $result['last_login_time'] = time();
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token))
                {
                    session('token', $token);
                }
                Db::name('user')->update($result);
                cookie("admin_username", $name, 3600 * 24 * 30);
                session("__LOGIN_BY_CMF_ADMIN_PW__", null);
                session('user', $result);
                $this->success(lang('LOGIN_SUCCESS'), url("portal/Index/index"));
            }
            else
            {
                $this->error(lang('PASSWORD_NOT_RIGHT'));
            }
        }
        else
        {
            $this->error(lang('USERNAME_NOT_EXIST'));
        }
    }

    /**
     * 后台管理员退出
     */
    public function logout()
    {
        session('PORTRL_ID', null);
        session('user', null);
        return redirect(url('/', [], false, true));
    }

    public function edituser(Request $request)
    {
        if ($request->isPost())
        {
            $param = $request->param();
            $userData = new UserModel();
            $user = $userData->where('id', session('user.id'))->find();

            if (cmf_compare_password($param['old_password'], $user['user_pass']))
            {
                if ($param['password'] === $param['re_password'])
                {
                    $userData['user_pass'] = cmf_password($param['password']);
                    $userData->save();
                    $this->success('修改成功!');
                }
                $this->error('两次密码不一致!');
            }
            else
            {
                $this->error('原始密码错误!');
            }
        }
        return $this->fetch('index:edituser');
    }
}
